package com.example.common.tools

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.content.ContextCompat
import io.reactivex.annotations.NonNull


/**
 * 权限申请
 */
class PermissionTool {

    companion object {
        private val mRequestCode = 100//权限请求码
        var showSystemSetting = true
        val instance by lazy(LazyThreadSafetyMode.NONE) {
            PermissionTool()
        }
    }

    private var mPermissionsResult: IPermissionsResult? = null


    fun chekPermissions(context: Activity, permissions:Array<String>, @NonNull permissionsResult: IPermissionsResult){
        this.mPermissionsResult = permissionsResult

        if (Build.VERSION.SDK_INT < 23) {
            permissionsResult.passPermissons()
            return
        }

        //创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
        var mPermissionList =  ArrayList<String>()
        //逐个判断你要的权限是否已经通过
        for (permis in permissions) {
            if (ContextCompat.checkSelfPermission(context, permis) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permis)//添加还未授予的权限
            }
        }

        //申请权限
        if (mPermissionList.size > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(context, permissions, mRequestCode)
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            permissionsResult.passPermissons()
            return
        }

    }

    /**
     * 未知来源apk安装
     */
    fun installApk(mContext:Activity,APPLICATION_ID:String){
        //兼容8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val hasInstallPermission: Boolean =
                mContext.packageManager.canRequestPackageInstalls()
            if (!hasInstallPermission) {
                val packageURI = Uri.parse("package:$APPLICATION_ID")
                //注意这个是8.0新API
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                mContext.startActivityForResult(intent, 1)
            } else {
                //再次执行安装流程，包含权限判等

            }
        }
    }


    fun onRequestPermissionsResult(context:Activity, requestCode:Int, @NonNull permissions:Array<String>,
    @NonNull grantResults:Array<Int>){
        var hasPermissionDismiss = false//有权限没有通过
        if (mRequestCode == requestCode) {
            for (results in grantResults) {
                if (results == -1) {
                    hasPermissionDismiss = true
                }
            }
            //如果有权限没有被允许
            if (hasPermissionDismiss) {
                if (showSystemSetting) {
                    showSystemPermissionsSettingDialog(context)//跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
                } else {
                    mPermissionsResult!!.forbitPermissons()
                }
            } else {
                //全部权限通过，可以进行下一步操作。。。
                mPermissionsResult!!.passPermissons()
            }
        }

    }

    private var mPermissionDialog: AlertDialog? = null
    private fun showSystemPermissionsSettingDialog(context: Activity){
        val mPackName = context.packageName
        if (mPermissionDialog == null) {
            mPermissionDialog =  AlertDialog.Builder(context)
                .setMessage("已禁用权限，请手动授予")
                .setPositiveButton("设置") { p0, p1 ->
                    cancelPermissionDialog()

                    var packageURI = Uri.parse("package:$mPackName")
                    var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                    context.startActivity(intent)
                    context.finish()
                }
                .setNegativeButton("取消"){p0, p1 ->
                    //关闭页面或者做其他操作
                    cancelPermissionDialog()
                    //mContext.finish();
                    mPermissionsResult!!.forbitPermissons()
                }
                .create()
        }
        mPermissionDialog!!.show()
    }

    //关闭对话框
    private fun cancelPermissionDialog() {
        if (mPermissionDialog != null) {
            mPermissionDialog!!.cancel()
            mPermissionDialog = null
        }
    }


    interface IPermissionsResult {
        fun passPermissons()

        fun forbitPermissons()
    }

}

